<template>
	<div class="login">
		<div class="login">
			<div class="main">
				<div class="content">
					<div class="left">
						<div class="left-top">
							<img src="../../assets/img/login/login_logo.png" alt="">
						</div>
						<div class="left-bottom">
							<img src="../../assets/img/login/login_data_bg.png" alt="">
						</div>
					</div>
					<div class="right">
						<div class="right-top">
							<div class="transferBox">
								<img src="../../assets/img/login/login_transfer.png" alt="">
							</div>
						</div>
						<div class="title">易控智驾数据管理平台</div>
						<div class="tabs">
							<div class="tabs-item" :class="{'active': loginWay === item.tab}" v-for="item in tabs" :key="item.tab" @click="tabClick(item.tab)">
								<span class="name">{{ item.name }}</span>
								<span class="divide"></span>
							</div>
						</div>
						<div class="formBox">
							<el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
								<template v-if="loginWay === 1">
									<el-form-item label="" prop="username">
										<el-input v-model.trim="searchForm.username" placeholder="请输入用户名" />
									</el-form-item>
									<el-form-item label="" prop="password">
										<el-input v-model.trim="searchForm.password" type="password" placeholder="请输入密码" autocomplete="off" />
									</el-form-item>
									<el-form-item label="" prop="authcode">
										<div class="authBox">
											<el-input v-model.number="searchForm.authcode" placeholder="请输入验证码" />
											<img :src="authcodeUrl" alt="" @click="getAuthCodeUrl">
										</div>
									</el-form-item>
								</template>
								<template v-if="loginWay === 2">
									<el-form-item label="" prop="phone">
										<el-input v-model.trim="searchForm.phone" placeholder="请输入手机号" />
									</el-form-item>
									<el-form-item label="" prop="authcode">
										<div class="authBox">
											<el-input v-model.number="searchForm.authcode" placeholder="请输入验证码" />
											<span v-if="!getAuthIng" class="authBtn" @click="getPhoneAuthCode">获取验证码</span>
											<span v-if="getAuthIng" class="authBtn">{{ seconds }}秒后重发</span>
										</div>
									</el-form-item>
								</template>
								<el-form-item>
									<span class="loginBtn" @click="submitForm('ruleForm')">登 录</span>
								</el-form-item>
							</el-form>
						</div>
					</div>
				</div>
			</div>
			<div class="footer">
				<span>@2022 北京易控智驾科技有限公司 版权所有 | 京ICP备 19030649号-2</span>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import useUserStore from '@/store/modules/user';
import { useRouter } from 'vue-router';

let timer = null;
const accessurl = window.location.protocol + "//" + window.location.host;

const useStore = useUserStore();
const router = useRouter();

const loginWay = ref(1);        // 登陆方式 1: 密码登录  2: 短信登录
const formRef = ref();
const authcodeUrl = ref('');
const errMsg = ref('');
const seconds = ref(60);
const getAuthIng = ref(false);

const tabs = reactive([
	{ name: '密码登录', tab: 1 },
	{ name: '短信登录', tab: 2 }
]);

const searchForm = reactive({
	username: '',
	password: '',
	phone: '',
	authcode: ''
});

const rules = reactive({
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
	phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
	authcode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
});

onMounted(() => {
	getAuthCodeUrl();
});

// 获取验证码
const getAuthCodeUrl = () => {
	const { APP_USER_URL } = window.config;
	const url = `${APP_USER_URL}userLogin/securityCode?d=${new Date().getTime()}`;
	authcodeUrl.value = url;
};

// 获取手机验证码
const getPhoneAuthCode = () => {
	ruleForm.value.validateField(
		"phone",
		(errorMessage) => {
			if (errorMessage.length) {
				getAuthIng.value = false;
			} else {
				getAuthIng.value = true;
				countDown();
			}
		}
	);
};

// 倒计时
const countDown = () => {
	let total = 60;
	seconds.value = total;

	timer = setInterval(() => {
		total--;
		seconds.value = total;
		if (seconds.value === 0) {
			clearInterval(timer);
			timer = null;
			getAuthIng.value = false;
		}
	}, 1000);

	sendAuthCode();
};

// 发送验证码
const sendAuthCode = () => {
	const params = {
		phoneNumber: searchForm.phone
	};

	sendSmsSign(params).then(res => {
		const { code, resultMsg } = res;
		if (code === 'success') {
			ElMessage({
				type: 'success',
				message: resultMsg || '验证码获取成功!'
			})
		} else {
			ElMessage({
				type: 'error',
				message: resultMsg || '验证码获取失败!'
			})
		}
	});
};

// 登录校验
const submitForm = (ruleForm) => {
	ruleForm.value.validate((valid) => {
		if (valid) {
			login();
		} else {
			return false;
		}
	});
};

// 登录
const login = () => {
	const { username, password, phone, authcode } = searchForm;

	let equal = {
		loginType: loginWay.value,
		accessUrl: accessurl,
	};

	if (loginWay === 1) {
		equal = {
			...equal,
			userName: username,
			password: password,
			imgCode: authcode
		}
	}

	if (loginWay === 2) {
		equal = {
			...equal,
			phone,
			smsCode: authcode
		}
	}

	const params = { equal };
	
	// useStore.login('user/login', params).then((res={}) => {
	//     const { code='', resultMsg='' } = res;
	//     if(code === 'success'){
	//         router.push('/home');
	//     }else{
	//         ElMessage({
	// 			type: 'error',
	// 			message: resultMsg || '登录失败!'
	// 		});
	//     }
	// });

	// this.$store.dispatch("user/login", params).then((res = {}) => {
	// 	const { code = '', resultMsg = '' } = res;
	// 	if (code === "success") {
	// 		this.$router.push({
	// 			path: this.redirect || "/",
	// 			query: this.otherQuery,
	// 		});
	// 	} else if (code === "PasswordExpiration") {
	// 		// 检测长时间未修改密码
	// 		// this.showDiaLog(resultMsg);
	// 	} else if (code === "IpInconsistent") {
	// 		this.errMsg = "您的账号异地登录，请使用手机验证码登录";
	// 		this.loginWay = "2";
	// 		this.ruleForm.phone = resultMsg;
	// 	} else {
	// 		this.errMsg = resultMsg;
	// 		this.getAuthCodeUrl();
	// 	}
	// });
};

const tabClick = (value) => {
	searchForm.authcode = '';
	loginWay.value = value;
};

</script>

<style lang="scss" scoped>
@import "./Login.scss";
</style>